package com.zyl.pagergallerysave_kt.viewModel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.zyl.pagergallerysave_kt.volley.VolleyUtil
import com.zyl.pagergallerysave_kt.pojo.PhotoItem
import com.zyl.pagergallerysave_kt.pojo.Pixabay

class GalleryViewModel(application: Application) : AndroidViewModel(application) {
    private val _photoLiveData = MutableLiveData<List<PhotoItem>>()
    val photoLiveData: LiveData<List<PhotoItem>> get() = _photoLiveData

//    init {
//        fetchData()
//    }

    fun fetchData() {
        val stringRequest: StringRequest = StringRequest(
                Request.Method.GET,
                getUrl(),
                Response.Listener {
                    _photoLiveData.value = Gson().fromJson(it, Pixabay::class.java).hits.toList()
                },
                Response.ErrorListener {
                    Log.e("myTAG", "fetchData: JSON加载失败", it)
                }
        )
        VolleyUtil.getVolleyUtil(getApplication()).requestQueue.add(stringRequest)

    }

    fun getUrl(): String {
        return "https://pixabay.com/api/?key=20367884-4ff0b66c3d8b80b87f646de62&q=${keyWork.random()}"
    }

    val keyWork: ArrayList<String> = arrayListOf("car", "cat", "pig", "photo")

}